import axios from 'axios'
import Vue from 'vue'
const instance = axios.create({
  timeout: 5000,
  baseURL: '/api'
})
instance.interceptors.request.use(request => {
  const accessToken = localStorage.getItem('access_token')
  accessToken && (request.headers.Access_token = accessToken)
  // console.log('request', request)
  return request
})
instance.interceptors.response.use(response => {
  // 请求成功是的处理模式
  if (response.status === 200) {
    if (response.data.access_token) {
      localStorage.setItem('access_token', response.data.access_token)
    }
    if (response.data.refresh_token) {
      localStorage.setItem('refresh_token', response.data.refresh_token)
    }
    return response.data
  }
}, error => {
  // const ERR_RES = error.response.config
  if (error.response) {
    if (error.response.status === 401) { // 401
      if (error.response.data.message === 'access invalid') {
        // token 被修改, 提示用户重新登录
        console.log('token被人为修改，去到登陆页面')
        Vue.$router.push('/login')
      } else if (error.response.data.message === 'access expired') {
        // token 过期
        console.log('access token 过期,重新获取token')
        // 获取 refresh,重新请求 access token
        const refreshToken = localStorage.getItem('refresh_token')
        // console.log(refreshToken)
        instance({
          url: '/get-access',
          headers: {
            'Refresh_token': refreshToken
          },
          method: 'get'
        }).then(res => {
          if (res.error_code === 1) {
            alert('刷新token失效,请重新登录')
          } else {
            console.log('重新获取access_token成功')
          }
        })
      }
    } else if (error.response.status === 403) { // 403
      // alert('请先登录')
      console.log('两种token都过期了，去到登陆页面')
      Vue.$router.push('/login')
    } else if (error.response.status === 404) { // 404
      // console.log(error.response.status === 404)
      alert('请求资源错误')
      // console.log('请求404了', error.response)
    } else if (error.response.status === 500) { // 500
      // console.log('请求500了', error.response)
    }
  }
})
export default instance
